package com.aier.user.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

import com.aier.common.dao.ICommonDAO;
import com.aier.proxy.service.IProxyService;
import com.aier.school.entity.School;
import com.aier.school.entity.mapper.SchoolRowMapper;
import com.aier.user.common.UserBillUtil;
import com.aier.user.entity.userapp.Bill;
import com.aier.user.entity.userapp.BillRowMapper;
import com.aier.user.entity.userapp.Commidity;
import com.aier.user.entity.userapp.CommidityRowMapper;
import com.aier.user.entity.userapp.Module;
import com.aier.user.entity.userapp.ModuleRowMapper;
import com.aier.user.entity.userapp.UserModule;
import com.aier.user.entity.userapp.UserModuleRowMapper;
import com.aier.user.service.IUserBuyService;

@Component("userBuyService")
public class UserBuyServiceImpl_J implements IUserBuyService{
    @Resource(name = "commonDao")
    private ICommonDAO commonDao;

    public void setCommonDao(ICommonDAO commonDao) {
        this.commonDao = commonDao;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<Long,Short> searchUserModState(Long uid){
        Map<Long,Short> stateMap = new HashMap<Long,Short>();
        List<Module> userapp_modules = (List<Module>) commonDao.list("select um.*," +
                "(select count(umid) from userapp_user_module where mid=um.mid and " +
                "uid=? and CURDATE() BETWEEN sdate and edate ) as num from userapp_module um;",
                new Object[]{uid}, new ModuleRowMapper(ModuleRowMapper.Module_AND_STATE));
        for(Module module:userapp_modules){
            stateMap.put(module.getMid(), module.getState());
        }
        return stateMap;
    }
    

    @Override
    public Bill insertBill(Long uid,Long commidity_id,int com_num) {
        Timestamp cdate = new Timestamp(new Date().getTime());
        int money_alone =  (int) commonDao.listByObject("select price from userapp_commodity where cid=? ",
                new Object[] { commidity_id}, new RowMapper<Integer>() {
                    @Override
                    public Integer mapRow(ResultSet rs, int arg1)
                        throws SQLException {
                        return rs.getInt("price");
                    }
                });
        int money = com_num*money_alone;
        
        Bill bill = new Bill();
        bill.setUid(uid);
        bill.setCid(commidity_id);
        bill.setNum(com_num);
        bill.setMoney(money);
        bill.setCdate(cdate);
        bill.setState(BILL_DOING);
        
        KeyHolder kh = commonDao.insert(
                BillRowMapper.getPreparedStatementCreator(bill),
                new GeneratedKeyHolder());
        bill.setBid(kh.getKey().longValue());
        
        return bill;
    }

    @Override
    public Bill searchBillById(Long bill_id){
        return (Bill) commonDao.listByObject("select * from userapp_bill where bid=?", 
                new Object[]{bill_id}, new BillRowMapper());
    }
    
    @Override
    public void updateBuyServiceSuccess(Long bill_id) {
        // 支付成功,1.更新订单状态为成功(判断是否已经是支付成功状态,避免重复执行);2.添加一条记录(userapp_user_module),加入有效期范围
        Bill bill = searchBillById(bill_id);
        if(bill!=null&&bill.getState()!=BILL_SUCCESS){
            commonDao.update("update userapp_bill SET state=? where bid=?",new Object[]{BILL_SUCCESS,bill_id});
            UserModule usermodule = (UserModule) commonDao.listByObject("select * from userapp_user_module where uid=? " +
            		"and mid=(select mid from userapp_commodity where cid=?)", 
                    new Object[]{bill.getUid(),bill.getCid()}, new UserModuleRowMapper());
            Date edate = null;
            Boolean flag = true;//标记 之前没有冲过值的
            if(usermodule!=null){
                edate = usermodule.getEdate();
                flag = false;
            }
            
            // 计算新的截止有效期
            edate = UserBillUtil.findNewEdate(bill.getCid(), bill.getNum(),edate );
            if(flag){
                commonDao.update("insert into userapp_user_module(uid,mid,edate) values(?,(select mid from userapp_commodity where cid=?),?)"
                    ,new Object[]{bill.getUid(),bill.getCid(),edate});
            }else{
                commonDao.update("update userapp_user_module set edate=? where uid=? and mid=(select mid from userapp_commodity where cid=?)"
                        ,new Object[]{edate,bill.getUid(),bill.getCid()});
            }
                    
        }else{
            System.out.println("bill:"+bill_id+" has success");
        }
        
    }

    @Override
    public void updateBuyServiceFail(Long bill_id) {
        // 支付失败,1.更新订单状态为失败;
        Bill bill = searchBillById(bill_id);
        if(bill!=null&&bill.getState()!=BILL_SUCCESS){
            commonDao.update("update userapp_bill SET state=? where bid=?",new Object[]{BILL_FAIL,bill_id});
        }
        
    }


    @SuppressWarnings("unchecked")
    @Override
    public List<Commidity> searchCommidityList(long mid) {
        return (List<Commidity>) commonDao.list("select * from userapp_commodity where mid=?", 
                new Object[]{mid}, new CommidityRowMapper());
    }


    @Override
    public Commidity searchCommidity(Long cid) {
        return (Commidity) commonDao.listByObject("select * from userapp_commodity where cid=?", 
                new Object[]{cid}, new CommidityRowMapper());
    }


    @Override
    public Map<String, Object> searchCommidityAll(int page, int page_size,
            int sortable) {
        
        String sql = "select * from userapp_commodity";
        switch (sortable) {
            case IProxyService.ENTRANCE_SORTABLE_SN:
                sql += " order by cid";
                break;
            case IProxyService.ENTRANCE_SORTABLE_SN_DESC:
                sql += " order by cid desc";
                break;
        }
        return commonDao.queryPage(sql,
                page, page_size, new Object[] {},
                new CommidityRowMapper());
    }
    
    @Override
    public Map<String, Object> searchUserBillList(int page, int page_size, Long uid){
        String sql = " FROM `userapp_bill` ub where ub.uid=? ";
        sql += " order by ub.cdate desc";
        String sql_first = sql;
        return commonDao.queryPage("SELECT ub.*,(select cname from userapp_commodity where cid=ub.cid) as commodity_name"+ sql, 
                "select count(*) " + sql_first, page,page_size, 
                new Object[] { uid }, new Object[] { uid },new BillRowMapper(BillRowMapper.AND_DATESTR));   
    }

    @Override
    public int deleteBill(Long bill_id) {
        commonDao.update("delete from userapp_bill where bid=?",new Object[] { bill_id });
        return 1;
    }
    
    @Override
    public UserModule searchUserModule(Long uid, Long mid){
        return (UserModule) commonDao.listByObject("select * from userapp_user_module where uid=? and mid=?", 
                new Object[] { uid,mid }, new UserModuleRowMapper());
    }

    @Override
    public String searchEdate(Long uid) {
        String edate = (String)commonDao.listByObject("select edate from userapp_user_module where uid=? and mid = 1", new Object[]{uid},
                new RowMapper<String>() {
                @Override
                public String mapRow(ResultSet rs, int arg1)
                    throws SQLException {
                    return rs.getString("edate");
                }
            }
        );
        return edate;
    }

    @Override
    public int searchSchoolBuyMethod(Long uid) {
        String method = (String)commonDao.listByObject("select s.method from school s left join classes c on s.sid = c.sid " +
        		"left join class_student cs on c.cid = cs.cid where cs.uid = ?", new Object[]{uid},
                new RowMapper<String>() {
                @Override
                public String mapRow(ResultSet rs, int arg1)
                    throws SQLException {
                    return rs.getString("method");
                }
            }
        );
        if (null == method || "".equals(method)) {
            return 1;
        } else {
            return Integer.valueOf(method);
        }
    }

    @Override
    public School searchSchoolMessageCount(Long cid) {
        return (School) commonDao.listByObject("select s.* from school s left join classes c on s.sid = c.sid where c.cid = ?", 
                new Object[] { cid }, new SchoolRowMapper());
    }

    @Override
    public School searchSchoolMessageCountSid(Integer sid) {
        return (School) commonDao.listByObject("select * from school where sid = ?", 
                new Object[] { sid }, new SchoolRowMapper());
        
    }

    
}
